package com.chorye.elastic.service;

import com.chorye.elastic.dao.StudentDao;
import com.chorye.elastic.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Company: 北京根网科技有限公司
 * @Author JiangYy
 * @Title: StudentService
 * @Description: TODO
 * @Date 2019/1/14 9:22
 */
@Service
public class StudentService {

    @Autowired
    private StudentDao studentDao;

    /**
     * 新增一个学生
     *
     * @return 新增的学生
     */
    public Student save() {
        Student student = new Student();
        student.setId(1);
        student.setName("NoSql保存测试");
        student.setBirth(new Date());
        student.setScore(66.66);
        return studentDao.save(student);
    }

    /**
     * 修改学生信息
     *
     * @return 修改后的学生信息
     */
    public Student update() {
        List<Student> students = studentDao.getByName("NoSql保存测试");
        if (CollectionUtils.isEmpty(students)) {
            return null;
        }
        Student student = students.get(0);
        if (student == null) {
            return null;
        }
        student.setName("NoSql修改测试");
        return studentDao.save(student);
    }

    /**
     * 删除学生信息
     */
    public void delete(Integer id) {
        studentDao.deleteById(id);
    }

    /**
     * 通过一个id查询学生
     *
     * @param id 学生id
     * @return 学生实体
     */
    public Student get(Integer id) {
        Optional<Student> student = studentDao.findById(id);
        return student.isPresent() ? student.get() : null;
    }

    /**
     * 查找所有学生
     *
     * @return 所有学生列表
     */
    public List<Student> selectAll() {
        Iterable<Student> all = studentDao.findAll();
        List<Student> students = new ArrayList<>();
        all.forEach(student -> students.add(student));
        return students;
    }

    /**
     * 根据名字删除学生
     *
     * @param name 名字
     */
    public void remove(String name) {
        studentDao.deleteByName(name);
    }
}
